const chapterHandler = require('../handlers/chapterHandler');
const api = require('../services/api');
var path = require('path');
var fs = require('fs');
var docx = require('docx');

const { AlignmentType, Document, HeadingLevel, Packer, Paragraph, TextRun, LevelFormat } = docx;

const process = async () => {

    let { response: { data: data } } = await api.getCourses();
    //find all course
    var courses = data.filter(x => x.content_type == "course").map(x => { return { id: x.content_id, title: x.title } });
    for (const course of courses) {
        console.log("==============================");
        console.log(course.title + " processing...");
        await processCourse(course);
    }
}

const processCourse = async (course) => {
    let { response: { data: [{ class_content: chapters }] } } = await api.getChaptersByCourseId(course.id);

    let index = 1;
    for (const item of chapters) {
        let filename = `0${index}-${item.title.replace("/", "").replace("/", "")}.docx`;
        console.log(filename + " processing...");
        let questions = await chapterHandler.processChapter(item.content.id);
        let output = path.join(__dirname, `../output/${course.title}`);
        await generateDoc(output, filename, questions);
        index++;
    }
}

const generateDoc = async (output, filename, questions) => {

    let paragraghs = [];
    questions.forEach((q) => {
        const question = new Paragraph({
            text: q.QuestionText,
            heading: HeadingLevel.HEADING_4,
            numbering: {
                reference: "my-numbering",
                level: 0
            }
        });

        paragraghs.push(question);

        paragraghs.push(...[
            new Paragraph({
                text: q.OptionA,
                numbering: {
                    reference: "my-numbering",
                    level: 1
                }
            }),
            new Paragraph({
                text: q.OptionB,
                numbering: {
                    reference: "my-numbering",
                    level: 1
                }
            }),
            new Paragraph({
                text: q.OptionC,
                numbering: {
                    reference: "my-numbering",
                    level: 1
                }
            }),
            new Paragraph({
                text: q.OptionD,
                numbering: {
                    reference: "my-numbering",
                    level: 1
                }
            })
        ]);

        q.OptionE && paragraghs.push(
            new Paragraph({
                text: q.OptionE,
                numbering: {
                    reference: "my-numbering",
                    level: 1
                }
            })
        );
        q.OptionF && paragraghs.push(
            new Paragraph({
                text: q.OptionF,
                numbering: {
                    reference: "my-numbering",
                    level: 1
                }
            })
        );

        paragraghs.push(...[
            new Paragraph({
                text: "Answer",
                heading: HeadingLevel.HEADING_5
            }),
            new Paragraph({
                children: [
                    new TextRun({
                        text: q.Anwser,
                        bold: true,
                    }),
                ]
            }),
            new Paragraph({
                text: q.Analysis
            })
        ]
        );
    });

    const doc = new Document({
        styles: {
            paragraphStyles: [
                {
                    id: "Heading4",
                    name: "Heading 4",
                    basedOn: "Normal",
                    next: "Normal",
                    quickFormat: true,
                    run: {
                        font: "Calibri",
                        size: 28,
                        italics: false,
                        color: "000000",
                    },
                    paragraph: {
                        spacing: {
                            after: 120,
                        },
                    },
                }]
        },
        numbering: {
            config: [
                {
                    reference: "my-numbering",
                    levels: [
                        {
                            level: 0,
                            format: LevelFormat.DECIMAL,
                            text: "%1.",
                            alignment: AlignmentType.START,
                        },
                        {
                            level: 1,
                            format: LevelFormat.UPPER_LETTER,
                            text: "%2.",
                            alignment: AlignmentType.START
                        }
                    ],
                },
            ],
        },
        sections: [{
            properties: {},
            children: paragraghs,
        }],
    });
    Packer.toBuffer(doc).then(buffer => {
        fs.mkdir(output, { recursive: true }, (error) => {
            fs.writeFileSync(output + "\\" + filename, buffer);
        });
    });
}

module.exports = {
    process
}